package com.xzc.algorithm.data_structure_ke.LinkedList;

import lombok.Data;

@Data
public class LinkListDummyHead<T> {

    @Data
    private static class Node<T> {
        private T t;
        private Node next;

        public Node(T t, Node next) {
            this.t = t;
            this.next = next;
        }

        public Node(T t) {
            this.t = t;
            this.next = null;
        }
    }

    private Node<T> DummyHead = new Node<T>(null);
    private int size = 0;

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(int index, T t) throws Exception {
        if (index < 0 || index > size)
            throw new Exception("error index");
        Node tmp = DummyHead;
        for (int i = 0; i < index; i++) {
            tmp = tmp.next;
        }
        tmp.next = new Node(t, tmp.next);
        size++;
    }

    public void addFirst(T t) throws Exception {
        add(0, t);
    }

    public void addLast(T t) throws Exception {
        add(size, t);
    }

    public T remove(int index) throws Exception {
        if (index < 0 || index > size - 1)
            throw new Exception("error index");
        if (isEmpty())
            throw new Exception("can't delete, empty now");
        Node<T> pre = DummyHead;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        Node<T> cur = pre.next;
        pre.next = cur.next;
        cur.next = null;
        size--;
        return cur.t;
    }

    public T removeFirst() throws Exception {
        return remove(0);
    }

    public T removeLast() throws Exception {
        return remove(size - 1);
    }

    public void set(int index, T t) throws Exception {
        if (index < 0 || index > size - 1)
            throw new Exception("error index");
        if (isEmpty())
            throw new Exception("can't delete, empty now");
        Node<T> pre = DummyHead;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next.t = t;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node tmp = DummyHead.next;
        for (int i = 0; i < size; i++) {
            sb.append(tmp.t).append(",");
            tmp = tmp.next;
        }
        sb.append("]");
        sb.append(" size=").append(size);
        return sb.toString();
    }
}
